package cn.huaqingcheng.tianshu.web.config;

import cn.huaqingcheng.tianshu.web.view.ErrorResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import jakarta.validation.ValidationException;
import jakarta.validation.constraints.NotNull;
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.util.ArrayList;
import java.util.List;

/**
 * GlobalBizExceptionHandler
 *
 * @author 清寒
 */
@Slf4j
@RestController
@RestControllerAdvice
public class GlobalBizExceptionHandler {


    /**
     * 兜底异常处理器 响应 {@code HTTP 500}
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public static ErrorResponse<String> exception(Exception e) {
        return logWarnResponseMessage(e);
    }

    /**
     * 通用异常消息处理 用于已知且不太重要的异常 (生产环境可以屏蔽这些日志)
     */
    private static @NotNull ErrorResponse<String> logWarnResponseMessage(Exception e) {
        log.warn(e.getLocalizedMessage(), e);
        return ErrorResponse.error(HttpStatus.INTERNAL_SERVER_ERROR, e.getLocalizedMessage(), e.getClass().getName());
    }

    /**
     * IOException 响应 {@code HTTP 500}
     */
    @ExceptionHandler(IOException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public static ErrorResponse<String> ioException(IOException e) {
        return logWarnResponseMessage(e);
    }

    /**
     * 访问被拒绝异常 响应 {@code HTTP 403}
     */
    @ExceptionHandler(AccessDeniedException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public ErrorResponse<String> accessDeniedException(AccessDeniedException e) {
        return logWarnResponseMessage(e);
    }

    /**
     * 参数绑定异常 响应 {@code HTTP 400}
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ErrorResponse<List<String>> bindException(BindException e) {
        return formatResponse(e);
    }

    /**
     * BindException 处理, 格式化错误消息
     */
    static ErrorResponse<List<String>> formatResponse(BindException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();

        List<String> errArgs = new ArrayList<>(10);
        for (FieldError error : fieldErrors) {
            String errArg = "%s.%s %s".formatted(error.getObjectName(), error.getField(), error.getDefaultMessage());
            log.debug(errArg);
            errArgs.add(errArg);
        }
        return ErrorResponse.error(HttpStatus.BAD_REQUEST, "参数错误", errArgs);
    }

    /**
     * Bean验证异常 响应 {@code HTTP 400}
     */
    @ExceptionHandler(ValidationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ErrorResponse<String> validationException(ValidationException e) {
        return logWarnResponseMessage(e);
    }

    /**
     * 方法参数类型不匹配异常 响应 {@code HTTP 400}
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ErrorResponse<String> methodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
        return logWarnResponseMessage(e);
    }

    /**
     * 缺失的Servlet请求参数异常 响应 {@code 400}
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ErrorResponse<String> missingServletRequestParameterException(MissingServletRequestParameterException e) {
        return logWarnResponseMessage(e);
    }

    /**
     * HTTP消息不可读异常 响应 {@code HTTP 400}
     * <p>
     * 一般是缺少必须的请求正文
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ErrorResponse<String> httpMessageNotReadableException(HttpMessageNotReadableException e) {
        return logWarnResponseMessage(e);
    }

    /**
     * 不支持的 HTTP 请求方法异常 响应 {@code HTTP 404}
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ErrorResponse<String> httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        return logWarnResponseMessage(e);
    }

    /**
     * 非法参数异常 响应 {@code HTTP 400}
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ErrorResponse<String> illegalArgumentException(IllegalArgumentException e) {
        return logWarnResponseMessage(e);
    }

    /**
     * 非法状态异常 响应 {@code HTTP 417}
     */
    @ExceptionHandler(IllegalStateException.class)
    @ResponseStatus(HttpStatus.EXPECTATION_FAILED)
    public ErrorResponse<String> illegalStateException(IllegalStateException e) {
        return logWarnResponseMessage(e);
    }

}
